package cz.data.common.handlers;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class ArrayToStringTypeHandler extends BaseTypeHandler<List<String>> {
    private static final String delimiter = ",";

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> objects, JdbcType jdbcType) throws SQLException {
        String data = Objects.isNull(objects) ? null : String.join(delimiter, objects);
        preparedStatement.setString(i, data);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return getList(resultSet.getString(s));
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return getList(resultSet.getString(i));
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return getList(callableStatement.getString(i));
    }

    public List<String> getList(String data) {
        if (data == null)
            return Collections.emptyList();
        try {
            String[] split = data.split(delimiter);
            return Stream.of(split).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Collections.emptyList();
    }
}
